package com.xiaoyu.base.remoteconfig;

import android.content.Context;

import in.srain.cube.app.init.InitializableAsync;
import in.srain.cube.app.init.InitializableSync;
import com.xiaoyu.base.remoteconfig.base.ConfigLinkedDataUpdater;
import com.xiaoyu.base.remoteconfig.base.ConfigValueGetter;

public class RemoteConfigClient implements ConfigValueGetter, InitializableAsync, InitializableSync, ConfigLinkedDataUpdater {

    private static final RemoteConfigClient INSTANCE = new RemoteConfigClient();

    private final ConfigValues mValues;
    private final ConfigLoader mLoader;
    private volatile boolean mInitialized;
    private ConfigLinkedDataUpdater mUpdater;

    private RemoteConfigClient() {
        this.mValues = new ConfigValues();
        this.mLoader = new ConfigLoader(mValues);
        this.mValues.setConfigLinkedDataUpdater(this);
    }

    public static RemoteConfigClient getInstance() {
        return INSTANCE;
    }

    public static RemoteConfigClient init(ConfigLinkedDataUpdater updater) {
        INSTANCE.setUpdater(updater);
        return INSTANCE;
    }

    public void setUpdater(ConfigLinkedDataUpdater updater) {
        this.mUpdater = updater;
    }

    public void compareHash(String other) {
        if (!mInitialized) {
            return;
        }
        if (mLoader.isRequesting()) {
            return;
        }
        if (!mValues.isShouldRefreshHash(other)) {
            return;
        }
        refresh();
    }

    public void refresh() {
        mLoader.readFromRemote();
    }

    public boolean isInitialized() {
        return mInitialized;
    }

    @Override
    public int getInt(String key, int def) {
        return mValues.getInt(key, def);
    }

    @Override
    public boolean getBoolean(String key, boolean def) {
        return mValues.getBoolean(key, def);
    }

    @Override
    public String getString(String key, String def) {
        return mValues.getString(key, def);
    }

    @Override
    public long getLong(String key, int def) {
        return mValues.getLong(key, def);
    }

    @Override
    public double getDouble(String key, double def) {
        return mValues.getDouble(key, def);
    }

    @Override
    public void update() {
        if (mUpdater != null) {
            mUpdater.update();
        }
    }

    @Override
    public void initiateSync(Context context) {
        mLoader.readFromLocal();
        mInitialized = true;
    }

    @Override
    public void initiateAsync(Context context) {
        mLoader.readFromRemote();
    }
}
